package com.example.testtouch2;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;

import com.demo.androidgame.fx.Game;
import com.demo.androidgame.fx.Input.TouchEvent;
import com.demo.androidgame.fx.gl.Camera2D;
import com.demo.androidgame.fx.gl.FPSCounter;
import com.demo.androidgame.fx.gl.SpriteBatcher;
import com.demo.androidgame.fx.impl.GLScreen;
import com.demo.androidgame.fx.math.OverlapTester;
import com.demo.androidgame.fx.math.Rectangle;
import com.demo.androidgame.fx.math.Vector2;

public class TestScreen extends GLScreen {

	public static float sencingTime = 0.3f;

	static final int GAME_READY = 0;
	static final int GAME_RUNNING = 1;
	static final int GAME_LEVEL_END = 2;
	static final int GAME_OVER = 3;
	static final int GAME_SCORE = 4;

	Camera2D guiCam;
	SpriteBatcher batcher;
	Rectangle playRect;
	Rectangle touchRect;
	Vector2 touchPoint, tmp, detachPoint, tmppoint;
	World world;
	// WorldListener worldListener;
	WorldRenderer renderer;
	boolean PLAYER_TOUCHED = false;

	float init = 60.0f;
	float lastTimer;
	int lastScore;
	int lastPoint0 = 0;
	int BDx, BDy;
	int state;

	SettingsColliderIO settingsColliderIO;
	
	String timer = "60";
	String scoreString = "0";
	String TimerString = "0";
	String PointString = "0";

	FPSCounter fpsCounter;
	static boolean nfcCheck = false;
	public static boolean level1 = true;
	public static boolean level2, lelvel3, level4 = false;

	boolean firstSence;

	// boolean demo = true;

	public TestScreen(Game game) {
		super(game);

		guiCam = new Camera2D(glGraphics, 720, 1280);
		batcher = new SpriteBatcher(glGraphics, 100);
		playRect = new Rectangle(360, 360, 100, 100);
		touchRect = new Rectangle(0, 0, 150, 150);
		touchPoint = new Vector2();
		detachPoint = new Vector2();
		tmp = new Vector2();
		tmppoint = new Vector2();
		world = new World(/* worldListener */);
		renderer = new WorldRenderer(glGraphics, batcher, world, world.gameLevel);

		lastScore = 0;
		scoreString = "0";
		lastTimer = 60;
		TimerString = "60";

	}

	@Override
	public void update(float deltaTime) {

		switch (state) {
		case GAME_READY:
			updateReady();
			break;
		case GAME_RUNNING:
			updateRunning(deltaTime);
			break;
		case GAME_LEVEL_END:
			updateLevelEnd();
			break;
		case GAME_OVER:
			updateGameOver();
			break;

		}
		
		
	}

	private void updateReady() {
		if (game.getInput().getTouchEvents().size() > 0) {
			state = GAME_RUNNING;

		}
	}

	static final String id= "dltjdn";
	static final String  passwd= "890321";
	private void updateRunning(float deltaTime) {
		if (Settings.soundEnabled)
			Assets.music.play();
		init -= deltaTime;

		if (world.score != lastScore) {

			lastScore = world.score;
			scoreString = "" + lastScore;

		}
		if (world.point0 != lastPoint0) {
			lastPoint0 = world.point0;
			PointString = "" + lastPoint0;
		}
		if ((int) init == 0) {
			state = GAME_OVER;

			if (lastScore >= Settings.highscores[4]) {
				// scoreString = "new highscore: " + lastScore;
				// else
				// scoreString = "" + lastScore;
				Settings.addScore(lastScore);
				Settings.addPoint(lastPoint0);
				Settings.save(game.getFileIO());
			}
		}

		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		game.getInput().getKeyEvents();
		Vector2 startPoint = new Vector2();

		int len = touchEvents.size();

		if (firstSence) {
			sencingTime += deltaTime;
			if (sencingTime >= 0.3f) {
				firstSence = false;
				sencingTime = 0.0f;
			}
		}

		for (int i = 0; i < len; i++) {

			TouchEvent event = touchEvents.get(i);
			touchPoint.set(event.x, event.y);
			guiCam.touchToWorld(touchPoint);
			if (event.type == TouchEvent.TOUCH_DOWN) {
				if (!PLAYER_TOUCHED && OverlapTester.pointInRectangle(world.player.bounds,
								World.boxInt(touchPoint))) {
					PLAYER_TOUCHED = true;
					firstSence = true;
					startPoint.set(touchPoint);
				} else
					break;
				tmp.set(startPoint);
			}
			if (event.type == TouchEvent.TOUCH_UP) {
				PLAYER_TOUCHED = false;
				world.isCollision = false;
				
//				(new Thread(new Runnable() {
//					public void run() {
//						try {
//							
//							String path = "http://172.16.3.16:8080/demoserver/getxml.action?id=%s&passwd=%s";
//
//							path = String.format(path, id,	passwd);
//
//							URL url = new URL(path);// 연결 설정
//							URLConnection conn = url.openConnection();// 연결
//							conn.getContent();// 데이터 송신
//						} catch (Exception ex) {
//						}
//					}
//				})).start();
				
			}
		}
		world.update(deltaTime, tmp, World.boxInt(touchPoint), PLAYER_TOUCHED, firstSence);

		if (world.levelup) {
			state = GAME_LEVEL_END;
		}

	}

	private void updateLevelEnd() {
//		Assets.music.pause();
		// 아직안했음! Assets 으로 level up 표시 할 것!
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent event = touchEvents.get(i);
			if (event.type != TouchEvent.TOUCH_UP)
				continue;
			world.gameLevel += 1;
			SettingsColliderIO.load(game.getFileIO());
			this.world = new World(/* worldListener */);
			world.gameLevel += 1;
			
			init = 60;
//			world.score += 10;

			world.score = (lastScore +10);
			world.point0 = lastPoint0;
			
			this.renderer = new WorldRenderer(glGraphics, batcher, world, world.gameLevel);
//			game.setScreen(new Level2Screen(game));
						
			state = GAME_READY;

		}
	}

	private void updateGameOver() {
		Assets.music.pause();
		// if(lastScore >= Settings.highscores[4]) {
		// scoreString = "new highscore: " + lastScore;
		// else
		// scoreString = "" + lastScore;
		// Settings.addScore(lastScore);
		// Settings.addPoint(lastPoint0);
		// Settings.save(game.getFileIO());}
		// Log.d(TimerString, scoreString);
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent event = touchEvents.get(i);
			if (event.type != TouchEvent.TOUCH_UP)
				try {

					Thread.sleep(3000);

				} catch (InterruptedException e) {
					e.printStackTrace();

				}
			game.setScreen(new menuScreen(game));
		}

	}

	@Override
	public void present(float deltaTime) {
		GL10 gl = glGraphics.getGL();
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		gl.glEnable(GL10.GL_TEXTURE_2D);

		renderer.render();
		guiCam.setViewportAndMatrices();
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		batcher.beginBatch(Assets.atlas);
		switch (state) {
		case GAME_READY:
			presentReady();
			break;
		case GAME_RUNNING:
			presentRunning();
			break;
		case GAME_LEVEL_END:
			presentLevelEnd();
			break;
		case GAME_OVER:
			presentGameOver();
			break;
		}
		// batcher.endBatch();

		gl.glDisable(GL10.GL_BLEND);
		// fpsCounter.logFrame();
	}

	private void presentLevelEnd() {

		batcher.beginBatch(Assets.atlas);
		batcher.drawSprite(340, 600, 300, 300, Assets.smile);
		batcher.endBatch();
		
	}

	private void presentGameOver() {
		batcher.beginBatch(Assets.atlas);
		batcher.drawSprite(340, 600, 300, 120, Assets.gameover);
		batcher.endBatch();
		if (Settings.soundEnabled = true) {
			Assets.music.stop();
			Assets.GameOverSound.play(1.0f);

		}
	}

	private void presentReady() {
		
		if(world.gameLevel ==1){
		batcher.beginBatch(Assets.atlas);
		batcher.drawSprite(340, 600, 300, 120, Assets.level1);
		batcher.endBatch();}
		
		else if(world.gameLevel == 2){
		batcher.beginBatch(Assets.atlas);
		batcher.drawSprite(340, 600, 300, 120, Assets.level2start);
		batcher.endBatch();}

	}

	private void presentRunning() {

		batcher.beginBatch(Assets.atlas);
		batcher.drawSprite(70, 1280 - 40, 140, 70, Assets.score);
		batcher.drawSprite(580, 1280 - 40, 140, 70, Assets.timer);
		batcher.endBatch();

		// int leng = world.present1s.size();
		// for(int j = 0; j< leng; j++){
		// Present present1 = world.present1s.get(j);
		// if(level1 == true){
		// batcher.beginBatch(Assets.present);
		// /**대충 run 돌려보면 어디서 문젠지 짐작갈꺼야. 선물 두개 먹으면 오류뜨지만 일부러 잘 못된거 이해하기 쉬운상태로
		// commit하는 거임
		// batcher.drawSprite(world.present1s.get(j).position.x,
		// world.present1s.get(j).position.y, World.X_BOX, World.Y_BOX,
		// Assets.present1);
		// 이걸 쓰고 싶은데
		// for문이 이런식으로 걸리면 4개가 한 자리에 겹쳐져서 마지막줄만 출력이 되고
		// j대신 0,1,2,3 다 나누면 색4개로 나오는데 충돌에서 문제가 되고...
		//
		// 일단 world의 충돌체크에서 내림차순으로 해야될거같고, for문도 다른방식으로 바꿔야될거같고...
		// 머리 좀만쓰면 알거같기도한데, 지금 머리도 굳었고 효율성을 위해 너에게 넘기겠음.ㅋ
		// **/
		// batcher.drawSprite(world.present1s.get(0).position.x,
		// world.present1s.get(0).position.y, World.X_BOX, World.Y_BOX,
		// Assets.present1); }
		// batcher.drawSprite(world.present1s.get(1).position.x,
		// world.present1s.get(1).position.y, World.X_BOX, World.Y_BOX,
		// Assets.present2);
		// batcher.drawSprite(world.present1s.get(2).position.x,
		// world.present1s.get(2).position.y, World.X_BOX, World.Y_BOX,
		// Assets.present3);
		// batcher.drawSprite(world.present1s.get(3).position.x,
		// world.present1s.get(3).position.y, World.X_BOX, World.Y_BOX,
		// Assets.present4);
		// batcher.endBatch();
		// }

		// else if(level1 != true){
		// batcher.drawSprite(present1.position.x, present1.position.y,
		// World.X_BOX, World.Y_BOX, Assets.present2);
		// batcher.drawSprite(present1.position.x, present1.position.y,
		// World.X_BOX, World.Y_BOX, Assets.present3);
		// batcher.drawSprite(present1.position.x, present1.position.y,
		// World.X_BOX, World.Y_BOX, Assets.present4);
		// }

		// gl0.glDisable(GL10.GL_BLEND);

		// nfc
		if (nfcCheck == true) {
			batcher.beginBatch(Assets.atlas);
			batcher.drawSprite(320, 1280 - 40, 140, 70, Assets.point0);
			batcher.endBatch();
		}
		// Log.d("timer", Integer.toString((int) init));
		timer = Integer.toString((int) init);

		if ((int) init == 0) {
			state = GAME_OVER;
		}
		batcher.beginBatch(Assets.items);
		Assets.font.drawText(batcher, timer, 640, 1280 - 40);
		Assets.font.drawText(batcher, scoreString, 200, 1280 - 40);
		batcher.endBatch();
		// nfc
		if (nfcCheck == true) {
			Assets.font2.drawText(batcher, PointString, 440, 1280 - 40);
			batcher.endBatch();
		}
	}

	// }
	@Override
	public void pause() {
		Settings.save(game.getFileIO());
	}

	@Override
	public void resume() {
	}

	@Override
	public void dispose() {
	}
}